package models;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.DomainAnalytic;

public class DomainAnalyticModel {
	
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "analytic_";
	
	private static DomainAnalyticModel instance = null;
	
	public static DomainAnalyticModel getInstance() {
		if (instance == null) {
			instance = new DomainAnalyticModel();
		}
		
		return instance;
	}
	
	public DomainAnalyticModel() {
		try {
			ObjectifyService.register(DomainAnalytic.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		/*try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }*/
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	
	public void insert(DomainAnalytic analytic) {
		if (cache != null) {
			cache.put(prefix + analytic.getDomain(), analytic);
		}
		ofy.put(analytic);
	}
	
	public DomainAnalytic get(String domain) {
		DomainAnalytic analytic = new DomainAnalytic();
		
		if (cache != null && cache.containsKey(prefix + domain)) {
			analytic = (DomainAnalytic) cache.get(prefix + domain);
		} else {
			try {
				analytic = ofy.get(new Key<DomainAnalytic>(DomainAnalytic.class, domain));
				if (cache != null) {
					cache.put(prefix + domain, analytic);
				}
			} catch (Exception e) {
				analytic = null;
			}
		}
		return analytic;
	}
	
	public void delete(DomainAnalytic analytic) {
		if (cache != null && cache.containsKey(prefix + analytic.getDomain())) {
			cache.remove(prefix + analytic.getDomain());
		}
		ofy.delete(analytic);
	}
}
